import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import Vue from 'vue'
import {getToken} from '@/utils/auth'
import config from '@/utils/config'
import Router from '@/router/index'

// 创建请求对象
const service = axios.create({
 // baseURL: config.api, // url = base url + request url
  timeout: 10000 ,// request timeout
  withCredentials: true,// 跨域
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发出请求前做点什么
    if (store.getters.token) {
      // 让每个请求携带令牌
      // “X-Token”是自定义头密钥
      // 请根据当前情况修改
     // config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // 处理请求错误
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  /**
   *如果您想要获取诸如头或状态之类的http信息
   *请返回response=>response
   */

  /**
   *通过自定义代码确定请求状态
   *这里只是一个例子
   *您还可以通过HTTP状态代码判断状态
   */

  response => {
    const res = response.data

    if ( res.status === "failure") {
      debugger
      switch (res.errors[0].errCode) {
        case "400":
          break
        case "401":
          Message({
            message: res.errors[0].errMsg|| 'Error',
            type: 'error',
            duration: 3 * 1000
          })
          // Vue.$router.push({path: '/login'});
          setCookie("token", "", -1);
          window.location.href = '/login';
          break
        case "403":
          Message({
            message: '拒绝访问,权限不足'|| 'Error',
            type: 'error',
            duration: 4* 1000
          })

          break
        case "404":
          Message({
            message: '请求错误,未找到该资源'|| 'Error',
            type: 'error',
            duration: 4* 1000
          })
          break
        case "405":
          console.log('请求方法未允许')
          break
        case "406":
          Message({
            message: res.errors[0].errMsg|| 'Error',
            type: 'error',
            duration: 3 * 1000
          })
          break
        case "408":
          console.log('请求超时')
          break
        case 500:
          console.log('服务器端出错')
          break
        case 501:
          console.log('网络未实现')
          break
        case 502:
          console.log('网络错误')
          break
        case 503:
          console.log('服务不可用')
          break
        case 504:
          console.log('网络超时')
          break
        case 505:
          console.log('http版本不支持该请求')
          break
        default:
          console.log(`连接错误${err.response.status}`)
      }
      Message({
        message: res.errors[0].errMsg|| 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token 50012: Other clients logged in 50014: Token expired
      if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  err => {
    console.log(err.response)
    //alert(err.response)
    if (err && err.response) {

    } else {
      console.log('连接到服务器失败')
    }
    return Promise.resolve(err.response)
  })
function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}
export default service
